/**
 * 
 */
package gsm.cable.server.filters;

import gsm.cable.server.datastore.DataService;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @author acer
 * 
 */
public class GsmFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		ResponseWraper responseWraper = new ResponseWraper((HttpServletResponse) servletResponse, HttpServletResponse.SC_OK);
		beforRequestStart(servletRequest, responseWraper);
		chain.doFilter(servletRequest, responseWraper);
		afterRequestCompletiion(servletRequest, responseWraper);
	}

	private void beforRequestStart(ServletRequest servletRequest, ResponseWraper responseWraper) {
	}

	private void afterRequestCompletiion(ServletRequest servletRequest, ResponseWraper responseWraper) throws IOException {
		int statusCode = responseWraper.getStatusCode();
		if (statusCode == HttpServletResponse.SC_OK) {
			DataService.commitAsync();
			DataService.commit();
		} else {
			DataService.rollback();
			DataService.rollbackAsync();
			String message = responseWraper.getMessage();
			if (message != null) {
				responseWraper.getWriter().print(message);
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
